package com.calabar.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;

/**
 * <p/>
 * <li>Description: Post请求Http客户端</li>
 * <li>@author: zijian.wu</li>
 * <li>Date: 2018/03/29 13:52</li>
 */

public class HttpClientPost {
    /**
     * 日志记录
     */
    private static final Logger LOGGER = LogManager.getLogger(HttpClientPost.class);

    /**
     * 客户端
     */
    private static CloseableHttpClient CLIENT;

    /**
     * 获取客户端
     *
     * @return CloseableHttpClient
     */
    public static CloseableHttpClient getClient() {
        if (null == CLIENT) {
            CLIENT = HttpClients.createDefault();
        }
        return CLIENT;
    }

    /**
     * 关闭客户端
     */
    public static void closeClient() {
        try {
            CLIENT.close();
        } catch (IOException e) {
            LOGGER.error("CloseableHttpClient close failure");
        }
    }

    /**
     * post请求
     *
     * @param url  请求url
     * @param data json类型字符串数据
     * @return 响应内容
     */
    public static String post(String url, String data) throws Exception {
        //成功响应码开头
        final String successCodeHead = "2";

        //创建客户端
        CloseableHttpClient client = getClient();
        HttpPost post = new HttpPost(url);

        // 构造请求数据
        StringEntity entity = new StringEntity(data, ContentType.APPLICATION_JSON);
        post.setEntity(entity);

        //HTTP响应、响应状态码
        CloseableHttpResponse response = null;
        Integer statusCode = null;
        String responseContent = null;

        try {
            //执行post请求
            response = client.execute(post);
            //获取响应状态码
            statusCode = response.getStatusLine().getStatusCode();
            HttpEntity httpEntity = response.getEntity();
            responseContent = EntityUtils.toString(httpEntity, "UTF-8");

            if (!successCodeHead.equals(statusCode.toString().substring(0, 1))) {
                JSONObject error = JSON.parseObject(responseContent);
                String errorMessage = error.getJSONObject("error").getString("message");
                LOGGER.error(errorMessage);
                if (errorMessage.contains("No such name for \'metrics\'")) {
                    errorMessage = "No Information for the stdCode";
                }
                LOGGER.error("Request Exception：" + errorMessage);
                throw new Exception(errorMessage);
            }

        } catch (ClientProtocolException e) {
            LOGGER.error("Http Client ClientProtocolException",e);
        } catch (IOException e) {
            LOGGER.error("Http Client IOException",e);
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                LOGGER.error("response close failure",e);
            }
        }
        return responseContent;
    }

    /**
     * post请求
     *
     * @param url  请求url
     * @param data json类型字符串数据
     * @return 响应内容
     */
    public static boolean postReturnBoolean(String url, String data) throws Exception {
        //成功响应码开头
        final String successCodeHead = "2";

        //创建客户端
        CloseableHttpClient client = getClient();
        HttpPost post = new HttpPost(url);

        // 构造请求数据
        StringEntity entity = new StringEntity(data, ContentType.APPLICATION_JSON);
        post.setEntity(entity);

        //HTTP响应、响应状态码
        CloseableHttpResponse response = null;
        Integer statusCode = null;
        String responseContent = null;
        try {
            //执行post请求
            response = client.execute(post);
            //获取响应状态码
            statusCode = response.getStatusLine().getStatusCode();

            LOGGER.info("response code:" + statusCode);

            if (!successCodeHead.equals(statusCode.toString().substring(0, 1))) {
                HttpEntity httpEntity = response.getEntity();
                responseContent = EntityUtils.toString(httpEntity, "UTF-8");
                JSONObject error = JSON.parseObject(responseContent);
                String errorMessage = error.getJSONObject("error").getString("message");
                LOGGER.error(errorMessage);
                throw new Exception(errorMessage);
            } else {
                return true;
            }
        } catch (ClientProtocolException e) {
            LOGGER.error("Http Client ClientProtocolException",e);
        } catch (IOException e) {
            LOGGER.error("Http Client IOException",e);
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                LOGGER.error("response close failure",e);
            }
        }
        return false;
    }
}
